import React, { Component, useState, useEffect } from 'react'
import {
  NavBar,
  Icon,
  InputItem,
  WingBlank,
  WhiteSpace,
  Button,
  Modal
} from 'antd-mobile'
import './index.css'
import msg from './msg.png'
import { sendCode } from '../../api/login/sendCode'
import { verify_code } from '../../api/register/verify_phone'

let num = 5
export default function VerifyCode(props) {

  const [count, setcount] = useState(num)
  const [value, setvalue] = useState('')

  useEffect(() => {
    handlecount()
  }, [])

  function handlecount() {
    let timer = setInterval(() => {
      setcount((state) => {
        if (state === 1) {
          clearInterval(timer)
        }
        return state - 1
      })
    }, 1000);
    setcount(5)
  }

  function iptChange(e) {
    setvalue(e)
  }

  async function btnClick() {
    const result = await verify_code(props.phone, value.trim())
    console.log(result);
    if (result.data.success) {
      console.log(456);
      props.history.push('/registerVerifyPassword')
    } else {
      alert('验证码错误！请重新输入')
    }
  }

  async function codebtnClick() {
    await sendCode()
    handlecount()
  }



  return (
    <div className='wrap'>
      <NavBar
        mode='light'
        icon={<Icon type='left' color='#000' />}
        onLeftClick={() => props.history.goBack()}
      >
        硅谷注册
      </NavBar>
      <WhiteSpace size='lg'></WhiteSpace>

      <WingBlank size='lg'>
        <div className='img'>
          <img src={msg} alt='' />
        </div>
        <WhiteSpace size='lg'></WhiteSpace>
        <WingBlank size='lg'>
          <div>
            我们将以短信或电话的形式将验证码发送给您，请注意接听0575/025/0592/010等开头的电话
          </div>
        </WingBlank>
        <WhiteSpace size='lg'></WhiteSpace>

        <div className='code'>
          <InputItem clear placeholder='请输入手机验证码' value={value} onChange={iptChange}></InputItem>
          <button className={count < 1 ? 'active code-btn' : 'code-btn'} onClick={codebtnClick}>{count < 1 ? '重新发送' : `重新发送(${count}s)`}</button>
        </div>
        <WingBlank size='lg'>
          <Button className='code-next' type='warning' disabled={/^\d{6}$/.test(value) ? false : true} onClick={btnClick}>
            下一步
          </Button>
        </WingBlank>
        <WingBlank size='lg'>
          遇到问题了?
          <a href=''>请联系客服</a>
        </WingBlank>
      </WingBlank>
    </div>
  )

}
